<%@page import="com.vietnam.power.util.CKConfiguration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!-- Content Header (Page header) -->
<section class="content-header">
	<h1>
		<c:choose>
			<c:when test="${mode=='view'}">
				<spring:message code="admin.user.info.view" />
			</c:when>
			<c:when test="${mode=='edit'}">
				<spring:message code="admin.user.info.update" />
			</c:when>
			<c:when test="${mode=='changepassword'}">
				<spring:message code="admin.user.info.change.password" />
			</c:when>
			<c:otherwise>
				<spring:message code="admin.user.info.new" />
			</c:otherwise>
		</c:choose>
	</h1>
	<ol class="breadcrumb">
		<li><a href="goHomePage.html"><i class="fa fa-dashboard"></i> <spring:message code="admin.homepage.title" /></a></li>
		<li class="active"><spring:message code="admin.user.title" /></li>
	</ol>
</section>

<!-- Main content -->
<section class="content">
	<div class="row">
		<!-- left column -->
		<div class="col-md-12">
			<!-- general form elements -->
			<div class="box box-primary">
				<div class="box-header">
					<h3 class="box-title">
						<c:choose>
							<c:when test="${mode=='view'}">
								<spring:message code="admin.user.info.view" />
							</c:when>
							<c:when test="${mode=='edit'}">
								<spring:message code="admin.user.info.update" />
							</c:when>
							<c:when test="${mode=='changepassword'}">
								<spring:message code="admin.user.info.change.password" />
							</c:when>
							<c:otherwise>
								<spring:message code="admin.user.info.new" />
							</c:otherwise>
						</c:choose>
					</h3>
				</div>
				<!-- /.box-header -->
				<!-- form start -->
				<form:form role="form" action="saveUser.html" method="post" commandName="userInfo" onsubmit="return validateForm();">
					<div class="box-body">
						<form:hidden path="id" />
						<c:if test="${mode =='changepassword'}">
							<div class="form-group">
								<label><spring:message code="admin.user.info.new.password" /></label>
								<form:password placeholder="" class="form-control" path="password" />
							</div>
							<div class="form-group">
								<label><spring:message code="admin.user.info.match.password" /></label> <input type="password" placeholder="" class="form-control" id="reMatchPassword" />
							</div>
						</c:if>
						<c:if test="${mode !='changepassword'}">
							<div class="form-group">
								<label><spring:message code="admin.user.info.first.name" /></label>
								<form:input type="text" placeholder="" class="form-control" path="firstName" />
							</div>
							<div class="form-group">
								<label><spring:message code="admin.user.info.last.name" /></label>
								<form:input type="text" placeholder="" class="form-control" path="lastName" />
							</div>
							<div class="form-group">
								<label><spring:message code="admin.user.info.email" /></label>
								<form:input type="text" placeholder="" class="form-control" path="email" />
							</div>
							<div class="form-group">
								<label><spring:message code="admin.user.info.phone" /></label>
								<form:select class="form-control" path="countryCode">
									<c:forEach var="c" items="${countryList }">
										<form:option value="${c.phoneCode }"> (${c.phoneCode }) ${c.countryName }
								</form:option>
									</c:forEach>
								</form:select>
								<form:input type="text" placeholder="" class="form-control" path="phone" />
							</div>
							<div class="form-group">
								<label><spring:message code="admin.user.info.gender" /></label>
								<form:select class="form-control" path="gender">
									<form:option value="M"> <spring:message code="admin.user.info.male" />
								</form:option>
									<form:option value="F"> <spring:message code="admin.user.info.female" />
								</form:option>
								</form:select>
							</div>
							
							<div class="form-group">
								<form:checkbox path="enabled"></form:checkbox> <spring:message code="admin.user.info.enable" />
							</div>
							
							<div class="form-group">
								<label><spring:message code="admin.user.info.timezone" /></label>
								<form:select class="form-control" path="timezone">
									<c:forEach var="t" items="${timezoneList }">
										<form:option value="${t.timezone }"> ${t.timezone }
								</form:option>
									</c:forEach>
								</form:select>
							</div>
							<div class="form-group">
								<label><spring:message code="admin.user.info.country" /></label>
								<form:select class="form-control" path="country">
									<c:forEach var="c" items="${countryList }">
										<form:option value="${c.countryName }"> ${c.countryName }
								</form:option>
									</c:forEach>
								</form:select>
							</div>
							<div class="form-group">
								<label><spring:message code="admin.user.info.avatar" /></label>
								<button onclick="openUploadDialog();" type="button" class="btn btn-primary">
									<spring:message code="admin.form.button.upload" />
								</button>
								<form:hidden path="avatarId" />
								<div class="box">
									<div class="box-body">
										<a data-toggle="lightbox" data-gallery="multiimages"><img id="thumb" class="img-thumbnail"></a>
									</div>
								</div>
							</div>
							
							<c:if test="${mode ==null}">
								<div class="form-group">
									<label><spring:message code="admin.user.info.username" /></label>
									<form:input placeholder="" class="form-control" path="userName" />
								</div>
								<div class="form-group">
									<label><spring:message code="admin.user.info.new.password" /></label>
									<form:password placeholder="" class="form-control" path="password" />
								</div>
							</c:if>
						</c:if>
					</div>
					<!-- /.box-body -->
					<c:if test="${mode !='view' }">
						<div class="box-footer">
							<button class="btn btn-success" type="submit">
								<spring:message code="admin.form.button.submit" />
							</button>
							<c:choose>
								<c:when test="${mode == 'edit' }">
									<button class="btn btn-primary" type="button" onclick="history.back(1);">
										<spring:message code="admin.form.button.back" />
									</button>
								</c:when>
								<c:otherwise>
									<button class="btn btn-warning" type="reset">
										<spring:message code="admin.form.button.reset" />
									</button>
								</c:otherwise>
							</c:choose>
						</div>
					</c:if>
				</form:form>
				<c:if test="${mode =='view' }">
					<form:form>
						<div class="box-footer">
							<button class="btn btn-success" type="button" onclick="changePassword(${userInfo.id})">
								<spring:message code="admin.form.button.change.password" />
							</button>
							<button class="btn btn-success" type="button" onclick="updateUser(${userInfo.id})">
								<spring:message code="admin.form.button.edit" />
							</button>
							<button class="btn btn-primary" type="button" onclick="history.back(1);">
								<spring:message code="admin.form.button.back" />
							</button>
						</div>
					</form:form>
				</c:if>
			</div>
			<!-- /.box -->
		</div>
		<!--/.col (right) -->
	</div>
	<!-- /.row -->
</section>

<div id="upload-dialog" class="modal fade">
	<div class="modal-dialog">
		<div class="box box-solid box-primary modal-content">
			<div class="box-header modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<h4 class="modal-title">
					<spring:message code="admin.form.upload.dialog.header" />
				</h4>
			</div>

			<div class="modal-body">
				<form:form role="form" action="uploadFile.html" method="post" commandName="uploadedFile" enctype="multipart/form-data">
					<div class="box-body">
						<div class="form-group">
							<div id="drop">
								<label>File</label> <input type="file" name="multipartFile" class="btn btn-default" /> <label id="error-message"></label>
							</div>
						</div>
						<input type="hidden" id="fileFor" name="fileFor" value="AVATAR_IMAGE" /> <input type="hidden" name="replacedId" id="replacedId" value="" />
					</div>
				</form:form>
				<div class="progress progress-striped">
					<div id="progress" style="width: 0%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="20" role="progressbar" class="progress-bar progress-bar-primary">
					</div>
				</div>
				<div class="box">
					<div class="box-header">
						<h3 class="box-title">
							<spring:message code="admin.form.upload.dialog.crop.image" />
						</h3>
					</div>
					<div class="box-body">
						<img id="image" class="img-responsive"> <input type="hidden" id="x" name="x" /> <input type="hidden" id="y" name="y" /> <input type="hidden"
							id="w" name="w" /> <input type="hidden" id="h" name="h" />
					</div>
					<!-- /.box-body -->
					<div class="box-footer">
						<button type="button" class="btn btn-success" onclick="createThumb();">
							<spring:message code="admin.form.upload.dialog.crop.image" />
						</button>
					</div>
					<!-- /.box-footer-->
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">
					<spring:message code="admin.form.dialog.button.close" />
				</button>
			</div>
		</div>
	</div>
</div>

<!-- /.content -->
<script type="text/javascript">
	var ias;
	$(function() {
		if ('${mode}' == "changepassword") {
			$('#userInfo').attr('action','changePassword.html');
		} else {
			if ('${mode}' == "view") {
				$("#userInfo :input").attr('disabled', true);
				$('img#thumb').attr('src','${pageContext.servletContext.contextPath}/loadImage.html?type=THUMB&fileId='+$('#avatarId').val()+'&date='+new Date().getTime());
				$('img#thumb').parent().attr('href','${pageContext.servletContext.contextPath}/loadImage.html?type=FULL&fileId='+$('#avatarId').val()+'&date='+new Date().getTime()+'.jpg');
			}
			if ('${mode}' == "edit") {
				$('img#thumb').attr('src','${pageContext.servletContext.contextPath}/loadImage.html?type=THUMB&fileId='+$('#avatarId').val()+'&date='+new Date().getTime());
				$('img#thumb').parent().attr('href','${pageContext.servletContext.contextPath}/loadImage.html?type=FULL&fileId='+$('#avatarId').val()+'&date='+new Date().getTime()+'.jpg');
			}
		}
	});
	
	$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
	    event.preventDefault();
	    $(this).ekkoLightbox();
	});
	
	function updateUser(id) {
		window.location.href='updateUser.html?id='+id;
	}
	
	function changePassword(id) {
		window.location.href='changePassword.html?id='+id;
	}
	
	function openUploadDialog(){
		$('#upload-dialog').modal("show");
		// upload file
		$('#uploadedFile').fileupload({
			 dataType: 'json',
	        // This element will accept file drag/drop uploading
	        dropZone: $('#drop'),
	        progressall: function (e, data) {
	            var progress = parseInt(data.loaded / data.total * 100, 10);
	            $('#progress').css(
	                'width',
	                progress + '%'
	            );
	            $('#progress').html(progress + '%');
	        },
	        done: function (e, data) {
	        	if ($.isNumeric(data.result)) {
					$('#progress').html('<spring:message javaScriptEscape="true" code="admin.form.upload.completed" />');	
	        		$('#replacedId').val(data.result);
	        		$('img#image').attr('src','${pageContext.servletContext.contextPath}/loadImage.html?type=FULL&fileId='+data.result);
	        		ias = $('img#image').imgAreaSelect({ fadeSpeed: 200, aspectRatio: '215:215',handles: true, onSelectChange: preview,instance: true });
	        	} else {
	        		$('#error-message').html(data.result);
	        	}
	        },
	
	        fail:function(e, data){
	            // Something has gone wrong!
	        	$("#error-dialog").modal('show');
	        }
		});
		
		 $('#upload-dialog').on('hidden.bs.modal', function () {
			 if (ias) {
				 ias.setOptions({ hide: true });
				 ias.update();
			 }
      	})
	}
	
	function preview(img, selection) {
		 $('#x').val(selection.x1);
         $('#y').val(selection.y1);
         $('#w').val(selection.width);
         $('#h').val(selection.height);    
	}

	function checkCoords() {
		if (parseFloat($('#w').val()))
			return true;
		$('#info-dialog .modal-body').html('<spring:message javaScriptEscape="true" code="admin.form.upload.crop.image.error" />');
		$('#info-dialog').modal('show');
		return false;
	};
	
	function createThumb() {
		if (checkCoords()) {
			var data = "x="+Math.round($('#x').val())+"&y="+Math.round($('#y').val())+"&w="+Math.round($('#w').val())+"&h="+Math.round($('#h').val())+
			"&resizew="+$('img#image').width()+"&resizeh="+$('img#image').height()+"&fileId="+$('#replacedId').val()+'&fileFor='+$('#fileFor').val();
			
			console.log(data);
			$.ajax({
				url : 'cropFile.html',
				type : 'POST',
				dataType : 'text',
				//contentType : "application/json; charset=utf-8",
				data:data,
				success : function(response) {
					if (!response) {
						$('#upload-dialog').modal('hide');
						$('#avatarId').val($('#replacedId').val());
						//display thumb image
						$('img#thumb').attr('src','${pageContext.servletContext.contextPath}/loadImage.html?type=THUMB&fileId='+$('#avatarId').val()+'&date='+new Date().getTime());
						$('img#thumb').parent().attr('href','${pageContext.servletContext.contextPath}/loadImage.html?type=FULL&fileId='+$('#avatarId').val()+'&date='+new Date().getTime()+'.jpg');
					} else {
						$("#error-dialog").modal('show');
					}
				},
				error : function() {
					//$("#error-dialog .modal-body").html("L");
					$("#error-dialog").modal('show');
				}
			});
		}
	}
	
	function validateForm() {
		if ('${mode}' == 'changepassword') {
			if ($('#password').val().trim().length==0) {
				$('#password').css('border-color','red');
				return false;
			} else {
				$('#password').css('border-color','');
			}
			
			if ($('#reMatchPassword').val().trim().length==0 
					|| $('#reMatchPassword').val().trim() != $('#password').val().trim()) {
				$('#reMatchPassword').css('border-color','red');
				return false;
			} else {
				$('#reMatchPassword').css('border-color','');
			}
			
			return true;
		} else {
			if ($('#firstName').val().trim().length==0) {
				$('#firstName').css('border-color','red');
				return false;
			} else {
				$('#firstName').css('border-color','');
			}
			
			if ($('#lastName').val().trim().length==0) {
				$('#lastName').css('border-color','red');
				return false;
			} else {
				$('#lastName').css('border-color','');
			}
			
			if (!validateEmail($('#email').val().trim())) {
				$('#email').css('border-color','red');
				return false;
			} else {
				$('#email').css('border-color','');
			}
			
			if ($('#phone').val().trim().length==0) {
				$('#phone').css('border-color','red');
				return false;
			} else {
				$('#phone').css('border-color','');
			}
			
			if (!parseInt($('#avatarId').val())) {
				$('button[onclick="openUploadDialog();"]').attr("class","btn btn-danger");
				return false;
			} else {
				$('button[onclick="openUploadDialog();"]').attr("class","btn btn-primary");
			}
			return true;
		}
	}
	
</script>
